package net.dntuan.training.spring.mvc;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {

	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String getLoginPage() {
		logger.debug("user is redirected to The login page!");
		return "login";
	}

	@RequestMapping(value = "login", params = "error", method = RequestMethod.GET)
	public String getFailurePage(Model model, HttpSession session) {
		// show messages on login form if authentication failed
		Object obj = session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
		if (obj instanceof AuthenticationException) {
			logger.debug(obj.getClass().getName());
			AuthenticationException authException = (AuthenticationException) obj;
			logger.debug(authException.getMessage());
			model.addAttribute("message", new String(authException.getMessage()));
			session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
		}
		return "login";
	}

	@RequestMapping(value = "login", params = "logout", method = RequestMethod.GET)
	public String getLogoutPage() {
		// TODO can't delete session
		return "login";
	}

	@RequestMapping(value = "welcome")
	public String getWelcomePage(Model model) {
		if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {
			Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			if (obj instanceof UserDetails) {
				UserDetails userDetails = (UserDetails) obj;
				model.addAttribute("username", userDetails.getUsername());
				model.addAttribute("roles", userDetails.getAuthorities());
			}
		}
		return "welcome";
	}
}
